<template>
  <view class="addressBook">
    <topTitle title="通讯录" :isBack="false">
      <template #right>
        <i @tap="goTo('/pages/create/addFriend')"></i>
      </template>
    </topTitle>
    <view class="com">
      <!-- 搜索框 -->
      <search @update:searchValue="searchFn" />

      <!-- 新的好友 -->
      <view class="new" @tap="goTo('/pages/addressBook/newFriends')">
        <view><i></i>新的好友</view>
        <view>
          <u-badge
            class="dot"
            type="success"
            max="99"
            :value="friendApplyList?.length"
          ></u-badge>
        </view>
      </view>

      <!-- 好友列表 -->
      <view class="friendList">
        <!-- 按首字母分组 -->
        <view v-for="(items, letter) in friendList" :key="letter">
          <view>{{ letter }}</view>
          <view>
            <view v-for="(item, idx) in items" :key="idx" @tap="goDetail(item)">
              <up-avatar
                mode="aspectFill"
                :src="item.picture"
                size="50"
              ></up-avatar>
              <text>{{ item.notes || item.nick_name }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, computed, getCurrentInstance } from "vue";
import { onShow } from "@dcloudio/uni-app";

const instance = getCurrentInstance()?.appContext.config.globalProperties;

import { FriendApply, Friend } from "@/api/ImApi";
import { useStore } from "@/stores";
const store = useStore();
const latestData = computed(() => store.latestData);

// 进入聊天
const goDetail = async (item: any) => {
  instance?.goTo("/pages/chat/chat?user_id=" + item.user_id + "&Type=1");
};
watch(latestData, (newValue:any) => {
  // 通知消息
  if (newValue.Grade == 2) {
    FriendApplyFn();
    FriendFn();
  }
});

// 搜索值
let searchValue = ref<string>("");

// 搜索功能
const searchFn = (e: string) => {
  searchValue.value = e.trim();
};

// 申请好友列表
let friendApplyList = ref<Array<any>>(); // 新好友申请列表
const FriendApplyFn = async () => {
  if (uni.getStorageSync("FriendApply")) {
    friendApplyList.value = uni.getStorageSync("FriendApply");
  }
  friendApplyList.value = await FriendApply();
};

// 通讯录列表
let originalFriendList = ref<Record<string, any[]>>(); // 原始分组数据
let friendList = ref<Record<string, any[]>>(); // 动态展示的分组数据

// 获取通讯录数据并分组
const FriendFn = async () => {
  let friendList = uni.getStorageSync("originalFriendList");

  if (friendList) {
    originalFriendList.value = friendList;
    updateFriendList();
  }
  let res = await Friend();
  console.log(res);

  originalFriendList.value = res.originalFriendList;
  updateFriendList();
};

// 更新 friendList，根据 searchValue 过滤
const updateFriendList = () => {
  if (!searchValue.value) {
    // 如果没有搜索内容，展示完整列表
    friendList.value = originalFriendList.value;
    return;
  }

  // 搜索并生成新分组
  let filteredList: Record<string, any[]> = {};
  for (const key in originalFriendList.value) {
    const filteredItems = originalFriendList.value[key].filter((item) =>
      ((item.notes || item.nick_name) as string)
        .toLowerCase()
        .includes(searchValue.value.toLowerCase())
    );
    if (filteredItems.length > 0) {
      filteredList[key] = filteredItems;
    }
  }
  friendList.value = filteredList;
};

// 监听 searchValue 的变化，实时更新 friendList
watch(searchValue, () => {
  updateFriendList();
});

// 生命周期
onShow(() => {
  FriendApplyFn();
  FriendFn();
});
</script>
<style scoped lang="scss">
@import "../../static/scss/addressBook.scss";
</style>
